package com.plant.action;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;
import com.plant.entity.UgcComment;
import com.plant.entity.UgcLike;
import com.plant.entity.UgcUser;
import com.plant.service.HelpService;
import com.plant.service.HomePageService;
import com.plant.service.UserServic;
import com.plant.tool.DateUtils;
import com.plant.tool.SendMessage;
import com.plant.tool.Test;

@Controller
@RequestMapping(value="/home")
public class HomePageAction {
	@Resource(name = "homePageServiceImpl")
	private HomePageService homePageService;

	@Resource(name = "helpServiceImpl")
	private HelpService helpService;

	@Resource(name = "userInfoImlp")  //---用户个人方法
	private UserServic userServic;

	@RequestMapping(value="/likes")  //1--用户点赞
	@ResponseBody
	public Map<Object,Object> UgcLikes(String secret,String pust_val,UgcLike ul,HttpServletResponse response,HttpServletRequest request,Integer user_id,Integer content_type,Integer content_id,Integer current_user_id){
		response.setHeader("access-control-allow-origin","*");
		Map<Object,Object> map=new HashMap<Object, Object>();
		if(secret==null||pust_val==null||content_id==null||user_id==null||content_type==null||current_user_id==null){
			map.put("message", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdsc=md.md5calc(pust_val+"flower_duigu2016"); 
			if(secret.endsWith(mdsc)){
				List<Object> list=new ArrayList<Object>();
				ul.setToContentId(content_id);
				ul.setUserId(user_id);
				ul.setToContentType(content_type);
				ul.setToUserId(current_user_id);
				list=homePageService.LikesID(user_id, content_type, content_id, current_user_id);
				if(list.size()==0){
					SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String t=sim.format(new Date());
					GetIp getip=new GetIp();
					String ip=getip.getIp2(request);
					ul.setIp(ip);
					ul.setCreateTime(Timestamp.valueOf(t));
					boolean b=homePageService.AddLikes(ul);
					if(b){
						map.put("message", "点赞成功");
						map.put("state", 1);
					}else{
						map.put("message", "点赞失败");
						map.put("state", 0);
					}
					return map;
				}else{
					UgcLike u=new UgcLike();
					Integer uid=Integer.parseInt(list.get(0).toString());
					u.setId(uid);
					boolean b=homePageService.DeleteLikes(u);
					if(b){
						map.put("message", "取消点赞成功");
						map.put("state", 1);
					}else{
						map.put("message", "取消点赞失败");
						map.put("state", 0);
					}
					return map;
				}
			}else{
				map.put("message", "秘钥错误");
				map.put("state", 0);
				return map;	
			}
		}
	}

	@RequestMapping(value="/random_three_nonfriend_users")  //3..随机推荐3个陌生人
	@ResponseBody
	public Map<Object,Object> RandomThreeNoFriendUsers(Integer user_id,String secret,String pust_val,UgcUser uf,HttpServletRequest request){
		Map<Object,Object> map=new HashMap<Object, Object>();
		if(secret==null||pust_val==null||user_id==null){
			map.put("message", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdsc=md.md5calc(pust_val+"flower_duigu2016"); 
			if(secret.endsWith(mdsc)){
				uf.setId(user_id);
				List<Map<String,Object>> userinf=new ArrayList<Map<String,Object>>();
				List<Object> list3=new ArrayList<Object>();
				List<Object> list2=new ArrayList<Object>();
				list2=helpService.GetFriendUidByA(uf);
				list3=helpService.GetFriendUidByR(uf);
				list3.addAll(list2);
				list3.add(user_id);
				String ids=StringUtils.join(list3.toArray(),",");
				userinf=homePageService.NoFriendUserInf(ids);
				map.put("list", userinf);
				map.put("message", "随机推荐好友成功");
				map.put("state", 1);
				return map;
			}else{
				map.put("message", "秘钥错误");
				map.put("state", 0);
				return map;	
			}
		}
	}


	@RequestMapping(value="/test_random_three_nonfriend_users")  //3..随机推荐3个陌生人 包含多少个共同好友
	@ResponseBody
	public Map<Object,Object> RandomThreeNoFriendUsersI(Integer user_id,String secret,String pust_val,UgcUser uf,UgcLike ul,HttpServletResponse response,HttpServletRequest request,Integer content_type,Integer content_id,Integer current_user_id){
		response.setHeader("access-control-allow-origin","*");
		Map<Object,Object> map=new HashMap<Object, Object>();
		if(secret==null||pust_val==null||user_id==null){
			map.put("message", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdsc=md.md5calc(pust_val+"flower_duigu2016"); 
			if(secret.endsWith(mdsc)){
				uf.setId(user_id);
				List<Map<String,Object>> userinf=new ArrayList<Map<String,Object>>();
				List<Object> list3=new ArrayList<Object>();
				List<Object> list2=new ArrayList<Object>();
				list2=helpService.GetFriendUidByA(uf);
				list3=helpService.GetFriendUidByR(uf);
				list3.addAll(list2);
				list3.add(user_id);
				String ids=StringUtils.join(list3.toArray(),",");
				userinf=homePageService.NoFriendUserInf(ids);
				for (Map<String,Object> userid: userinf) {
					List<Object> list4=new ArrayList<Object>();
					List<Object> list5=new ArrayList<Object>();
					Integer uid=(Integer) userid.get("id");
					uf.setId(uid); 
					list4=helpService.GetFriendUidByA(uf);
					list5=helpService.GetFriendUidByR(uf);
					list5.addAll(list4);
					list5.addAll(list3);
					Integer uidlist=Test.CountSameList(list5);
					userid.put("common_friend_count", uidlist);
				}
				map.put("list", userinf);
				map.put("message", "随机推荐好友成功");
				map.put("state", 1);
				return map;
			}else{
				map.put("message", "秘钥错误");
				map.put("state", 0);
				return map;	
			}
		}
	}                                                                                                 


	@RequestMapping(value="/reply_comment")  //4---用户回复评论
	@ResponseBody
	public Map<Object,Object> ReplyComment(UgcUser uf,String secret,String pust_val,Integer current_user_id,Integer before_release_content_id,UgcComment uc,Integer reply_type,Integer user_id,String comment_content,Integer reply_comment_id,Integer reply_comment_user_id,HttpServletResponse response,HttpServletRequest request){
		response.setHeader("access-control-allow-origin","*");
		Map<Object,Object> map=new HashMap<Object, Object>();
		if(secret==null||pust_val==null){
			map.put("message", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdsc=md.md5calc(pust_val+"flower_duigu2016"); 
			if(secret.endsWith(mdsc)){
				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String t=sim.format(new Date());
				GetIp getip=new GetIp();
				String ip=getip.getIp2(request);
				if(reply_comment_id==null&&reply_comment_user_id==null){
					uc.setUserId(current_user_id);//---当前用户id
					uc.setContent(comment_content);//---评论文字
					uc.setToContentType(reply_type);//---这条内容的类型是什么？
					uc.setToContentId(before_release_content_id);//--评论给哪条内容？（内容的ID）
					uc.setToContentUserId(user_id);//这条内容是谁的？（他的用户ID）
					uc.setCreateTime(Timestamp.valueOf(t));
					uc.setIp(ip);
					uc.setReplyCommentId(0);//--回复哪条评论？（这条的评论ID）
					uc.setReplyCommentUserId(0);//--回复的给谁？（他的用户ID）
					boolean b=homePageService.AddComment(uc);
					if(b){
						if(current_user_id.equals(user_id)){
							map.put("message", "评论成功");
							map.put("state", 1);
						}else{
							uf.setId(user_id);
							UgcUser u=(UgcUser)userServic.OneUser(uf);
							if(u==null){
								map.put("mes", "用户为空");
							}else{
								String deviceToken=u.getDiviceToken();
								if(deviceToken.isEmpty()){
									map.put("mes", "用户TOKEN为空");
								}else{
									SendMessage send=new SendMessage();
									String mes=send.IosSendMessageNewThingComment(deviceToken,before_release_content_id);
									map.put("mes", mes);
								}
							}
						}
					}else{
						map.put("message", "评论失败");
						map.put("state", 0);
					}
				}else{
					uc.setUserId(current_user_id);//---当前用户id
					uc.setContent(comment_content);//---评论文字
					uc.setToContentType(reply_type);//---这条内容的类型是什么？
					uc.setToContentId(before_release_content_id);//--评论给哪条内容？（内容的ID）
					uc.setToContentUserId(user_id);//这条内容是谁的？（他的用户ID）
					uc.setCreateTime(Timestamp.valueOf(t));
					uc.setIp(ip);
					uc.setReplyCommentId(reply_comment_id);//--回复哪条评论？（这条的评论ID）
					uc.setReplyCommentUserId(reply_comment_user_id);//回复的给谁？（他的用户ID）
					boolean b=homePageService.AddComment(uc);
					if(b){
						if(current_user_id.equals(user_id)){
							map.put("message", "评论成功");
							map.put("state", 1);
						}else{
							uf.setId(user_id);
							UgcUser u=(UgcUser)userServic.OneUser(uf);
							if(u==null){
								map.put("mes", "用户为空");
							}else{
								String deviceToken=u.getDiviceToken();
								if(deviceToken.isEmpty()){
									map.put("mes", "用户TOKEN为空");
								}else{
									SendMessage send=new SendMessage();
									String mes=send.IosSendMessageNewThingComment(deviceToken,before_release_content_id);
									map.put("mes", mes);
								}
							}
						}
					}else{
						map.put("message", "评论失败");
						map.put("state", 0);
					}	
				}
				return map;
			}else{
				map.put("message", "秘钥错误");
				map.put("state", 0);
				return map;	
			}
		}
	}


	@RequestMapping(value ="moment")//----6首页动态
	@ResponseBody
	public Map<Object,Object> Moment(Integer user_id,Integer page,String first_page_time,UgcUser uf,HttpServletResponse response,String secret,String pust_val) throws BadElementException, MalformedURLException, IOException{
		response.setHeader("access-control-allow-origin","*");
		Map<Object,Object> map=new HashMap<Object,Object>();
		if(secret==null||pust_val==null||page==null||first_page_time==null||user_id==null){
			map.put("message", "请查看参数是否正确");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mds=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mds)){
				long starttime=System.currentTimeMillis();//---获取当前时间
				List<Object> list1=new ArrayList<Object>();
				Integer p=(page-1)*10;
				uf.setId(user_id);
				List<Object> list5=new ArrayList<Object>();
				List<Object> list2=new ArrayList<Object>();
				list2=helpService.GetFriendUidByA(uf);
				list5=helpService.GetFriendUidByR(uf);
				list5.addAll(list2);
				list5.add(user_id);
				String ids=StringUtils.join(list5.toArray(),",");
				List<Object[]> list=new ArrayList<Object[]>();
				List<Object[]> list4=new ArrayList<Object[]>();
				List<Object[]> likelist=new ArrayList<Object[]>();
				List<Object> imagelist=new ArrayList<Object>();
				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				DateUtils du=new DateUtils();
				list=userServic.Moment(ids, first_page_time, p);
				list4=userServic.Moment(ids, first_page_time, p+1);
				if(list4.size()>0){
					map.put("hasmore", 1);
				}else{
					map.put("hasmore", 0);
				}
				List<Object[]> list3=new ArrayList<Object[]>();
				for (int i = 0; i < list.size(); i++) {
					List<Object> imagesizelist=new ArrayList<Object>();
					List<Object> likeslist=new ArrayList<Object>();
					List<Object> commentlists=new ArrayList<Object>();
					List<Object[]> commentlist=new ArrayList<Object[]>();
					Map<Object,Object> map1=new HashMap<Object,Object>();
					Object[] obj=list.get(i);
					Integer content_type=Integer.parseInt(obj[4].toString());
					if(content_type==1){
						map1.put("id_key", obj[0]);
						map1.put("user_id", obj[1]);
						UgcUser uu=(UgcUser) userServic.UserPartInf(obj[1]);
						map1.put("user_name", uu.getNickname());
						map1.put("user_photo", uu.getPhoto());
						String t=sim.format(obj[2]);
						long l=du.getUnixStamps(t);
						map1.put("add_time",du.TopicCommentTime(l));
						map1.put("content_type", obj[4]);
						map1.put("content_type_zh", "上传照片");
						map1.put("content_text", obj[3]);
						imagelist=userServic.NewThingsImages(obj[0]);
						map1.put("images_list",imagelist);
						if(imagelist!=null){
							for (int j = 0; j < imagelist.size(); j++) {
								Map<Object,Object> map3=new HashMap<Object, Object>();
								String url=String.valueOf(imagelist.get(j));
								Image img = Image.getInstance(new URL(url));  
								map3.put("width", img.getWidth());
								map3.put("height", img.getHeight());
								imagesizelist.add(map3);	
							}
						}
						map1.put("images_size",imagesizelist);
						boolean b=homePageService.CheckLikes(uf, obj[1], obj[0]);
						if(b){
							map1.put("is_like", 1);
						}else{
							map1.put("is_like", 0);
						}
						likelist=homePageService.LikesList(ids,obj[0]);
						if(likelist!=null){
							for (int j = 0; j <likelist.size(); j++) {
								Map<Object,Object> map4=new HashMap<Object, Object>();
								Object[] objlikes=likelist.get(j);
								map4.put("user_id", objlikes[0]);
								map4.put("user_name", objlikes[1]);
								map4.put("user_photo", objlikes[2]);
								likeslist.add(map4);
							}
						}
						map1.put("like_list",likeslist);
						commentlist=homePageService.CommentList(ids,obj[0]);
						if(commentlist.size()!=0){
							for (int j = 0; j < commentlist.size(); j++) {
								Map<Object,Object> map5=new HashMap<Object,Object>();
								Object[] com=commentlist.get(j);
								map5.put("id_key",com[0]);
								map5.put("from_user_id", String.valueOf(com[1]));
								map5.put("from_user_name", com[4]);
								map5.put("content", com[2]);
								if(com[5].equals(0)){
									map5.put("to_user_id",String.valueOf(0));
									map5.put("to_user_name", "");
								}else{
									map5.put("to_user_id", String.valueOf(com[5]));
									UgcUser username=(UgcUser) userServic.UserPartInf(com[5]);
									map5.put("to_user_name", username.getNickname());
								}
								commentlists.add(map5);
							}
						}
						map1.put("comment_list",commentlists);
						list1.add(map1);
					}
					if(content_type==3){//---发布求助
						map1.put("id_key", obj[0]);
						map1.put("user_id", obj[1]);
						UgcUser uu=(UgcUser) userServic.UserPartInf(obj[1]);
						map1.put("user_name", uu.getNickname());
						map1.put("user_photo", uu.getPhoto());
						String t=sim.format(obj[2]);
						long l=du.getUnixStamps(t);
						map1.put("add_time",du.TopicCommentTime(l));
						map1.put("content_type", obj[4]);
						map1.put("content_type_zh", "发出求助");
						map1.put("content_text", obj[3]);
						map1.put("answer_count", userServic.FaqCountBid(obj[0]));
						imagelist=userServic.FaqImage(obj[0]);
						map1.put("images_list",imagelist);
						for (int j = 0; j < imagelist.size(); j++) {
							Map<Object,Object> map3=new HashMap<Object, Object>();
							String url=String.valueOf(imagelist.get(j));
							Image img = Image.getInstance(new URL(url));  
							map3.put("width", img.getWidth());
							map3.put("height", img.getHeight());
							imagesizelist.add(map3);
						}
						map1.put("images_size",imagesizelist);
						list1.add(map1);
					}
					if(content_type==4){
						map1.put("id_key", obj[0]);
						map1.put("user_id", obj[1]);
						UgcUser uu=(UgcUser) userServic.UserPartInf(obj[1]);
						map1.put("user_name", uu.getNickname());
						map1.put("user_photo", uu.getPhoto());
						String t=sim.format(obj[2]);
						long l=du.getUnixStamps(t);
						map1.put("add_time",du.TopicCommentTime(l));
						map1.put("content_type", obj[4]);
						map1.put("content_type_zh", "话题的参与");
						map1.put("content_text", obj[3]);
						UgcUser u=new UgcUser();
						u.setId(Integer.parseInt(obj[1].toString()));
						list3=userServic.TopicJoinInf(u, obj[0]);//---话题参与
						if(list3.size()==0){
							map1.put("topic_id", "");
							map1.put("topic_title", "");
							map1.put("topic_joined_people_count", "");
						}else{
							for (int j = 0; j < list3.size(); j++) {
								Object[] obj33=list3.get(j);
								map1.put("topic_id", obj33[0]);
								map1.put("topic_title", obj33[1]);
								map1.put("topic_joined_people_count", userServic.TopicJoinCountBid(obj33[0]));
							}
						}
						imagelist=userServic.TopicJoinImages(u,obj[0]);
						map1.put("images_list",imagelist);
						for (int j = 0; j < imagelist.size(); j++) {
							Map<Object,Object> map3=new HashMap<Object, Object>();
							String url=String.valueOf(imagelist.get(j));
							Image img = Image.getInstance(new URL(url));  
							map3.put("width", img.getWidth());
							map3.put("height", img.getHeight());
							imagesizelist.add(map3);
						}
						map1.put("images_size",imagesizelist);
						commentlist=homePageService.TopicCommentList(ids,obj[0]);//查看评论列表（话题参与）
						if(commentlist.size()!=0){
							for (int j = 0; j < commentlist.size(); j++) {
								Map<Object,Object> map5=new HashMap<Object,Object>();
								Object[] com=commentlist.get(j);
								map5.put("id_key",com[0]);
								map5.put("from_user_id", String.valueOf(com[1]));
								map5.put("from_user_name", com[4]);
								map5.put("content", com[2]);
								if(com[5].equals(0)){
									map5.put("to_user_id",String.valueOf(0));
									map5.put("to_user_name", "");
								}else{
									map5.put("to_user_id", String.valueOf(com[5]));
									UgcUser username=(UgcUser) userServic.UserPartInf(com[5]);
									map5.put("to_user_name",username.getNickname());
								}
								commentlists.add(map5);
							}
						}
						map1.put("comment_list",commentlists);//返回评论列表（话题）
						boolean b=homePageService.CheckTonpicJoinLikes(uf, obj[1], obj[0]);
						if(b){
							map1.put("is_like", 1);
						}else{
							map1.put("is_like", 0);
						}
						likelist=homePageService.TopicLikesList(ids,obj[0]);
						if(likelist!=null){
							for (int j = 0; j <likelist.size(); j++) {
								Map<Object,Object> map4=new HashMap<Object, Object>();
								Object[] objlikes=likelist.get(j);
								map4.put("user_id", objlikes[0]);
								map4.put("user_name", objlikes[1]);
								map4.put("user_photo", objlikes[2]);
								likeslist.add(map4);
							}
						}
						map1.put("like_list",likeslist);
						list1.add(map1);
					}
				}			
				map.put("timeline", list1);
				map.put("message", "ok");
				map.put("state", 1);
				long endtime=System.currentTimeMillis();
				System.out.println("程序执行的时间"+(endtime-starttime)+"ms");
				return map;
			}else{
				map.put("error", "秘钥错误");
				map.put("state", 1);
				return map;
			}
		}
	}
}
